<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片展示区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮部分 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表展示部分 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开层 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- for循环嵌套二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三层 -->
                  <el-col :span="18">
                    <!-- close事件可查询官方文档关闭tag触发closable与close一起使用 -->
                    <el-tag
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre> //查看数据结构
                {{ scope.row }}
                </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="success"
              icon="el-icon-delete"
              @click="removeRolesById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-s-tools"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 处理操作对话框 -->
      <!-- 添加用户对话框区域 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容 -->
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="80px"
        >
          <el-form-item label="角色ID" prop="roleId">
            <el-input v-model="addForm.roleId"></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改编辑用户角色对话框 -->
      <el-dialog
        title="编辑用户角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <!-- 编辑角色内容部分 -->
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="80px"
        >
          <el-form-item label="角色ID">
            <el-input v-model="editForm.roleId" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <!-- 编辑角色底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRolesInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 权限分配与管理对话框 -->
      <el-dialog
        title="权限分配"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="setRightDialogClose"
      >
        <!-- 内容 :data绑定数据 :props 树形控件的属性绑定对象 node-key每个节点绑定的值-->
        <el-tree
          :data="rightRolesList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          ref="treeRef"
        ></el-tree>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      roleList: [],
      addForm: {
        roleId: '',
        roleName: '',
        roleDesc: '',
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在2~10', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '描述名长度2~10', trigger: 'blur' },
        ],
      },
      dialogVisible: false,
      editDialogVisible: false,
      // 修改角色表单
      editForm: {},
      editFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度在2~10', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '描述名长度2~10', trigger: 'blur' },
        ],
      },
      setRightDialogVisible: false, //权限分配对话框
      rightRolesList: [], //分配权限数据
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName', //看到的是那个属性
        children: 'children', //父子属性按那个嵌套
      },
      //默认勾选的keys
      defKeys: [],
      // 当前选择权限分配的id
      roleId: '',
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 刷新列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    async showEditDialog(id) {
      // 一、展示通过id获取的表单
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败')
      }
      //    1.将查询的东西给表单
      this.editForm = res.data
      //    2.展示表单
      this.editDialogVisible = true
    },
    // 关闭添加用户角色面板
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户角色信息
    addRoles() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户角色失败')
        }
        this.dialogVisible = false
        this.getRolesList()
        this.$message.success('添加用户角色成功')
      })
    },

    // 二、当关闭对话框表单填写内容复原
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 判断输入框内容是否符合规则及修改角色内容
    editRolesInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改用户角色失败')
        }
        this.editDialogVisible = false // 2.关闭对话框
        this.getRolesList() //    1.刷新表单
        this.$message.success('修改用户角色成功')
      })
    },
    // 删除角色信息
    async removeRolesById(id) {
      // 弹框提示是否继续删除   只有一个返回值
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) //抓取错误信息

      if (confirmResult != 'confirm') {
        this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)

      if (res.meta.status != 200) {
        this.$message.error('删除用户失败')
      }
      this.$message.success('删除成功')
      this.getRolesList()
      //  const deleteRoles=await this.$http.delete('roles/' + id)
      //    if (!deleteRoles) {
      //         this.$message.error('角色删除失败')
      //    }
      //    this.getRolesList()
      //    this.$message.success('角色删除成功')
    },
    //删除tag 点击closeable触发close
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) //返回错误情况
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 删除成功需要的操作
      // console.log('删除成功');
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 只局部刷新数据 防止展开盒关闭
      role.children = res.data
    },
    //分配权限管理对话框
    async showSetRightDialog(role) {
      // 展示权限树
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      //  将获取的数据赋值给列表
      this.rightRolesList = res.data

      // 递归获取三级节点的id,渲染
      this.getLeafKeys(role, this.defKeys)
      // console.log(this.rightRolesList);
      this.setRightDialogVisible = true
    },
    // 通过递归调用获取角色id
    getLeafKeys(node, arr) {
      if (!node.children) {
        // 符合条件的将其id存入arr中
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 关闭对话框更新defKeys
    setRightDialogClose() {
      this.defKeys = []
    },
    // 获取全部选择节点的id和半选择节点的id
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getHalfCheckedNodes(),
        ...this.$refs.treeRef.getCheckedKeys(),
      ]
      // 元素将由指定的分隔符分隔。默认分隔符是逗号 (,)
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
